﻿/*
 * Author: Duncan Jenkins / Martijn Koopman
 * 
 * Description: Inverts the colors in a image
 * */

using System.Drawing;
using System.Drawing.Imaging;

namespace LibraryCS {
    public class InvertAlgorithm : VisionAlgorithm {
        public InvertAlgorithm(string name) : base(name) { }

        public override Bitmap DoAlgorithm(Bitmap sourceImage) {
            Bitmap image = new Bitmap(sourceImage.Width, sourceImage.Height);
            Rectangle rect = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
            BitmapData source = sourceImage.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
            BitmapData dest = image.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);

            unsafe {
                int* sourcePtr = (int*)source.Scan0;
                int* destPtr = (int*)dest.Scan0;
                int length = (source.Stride * source.Height) / 4;
                for (int i = 0; i < length; i++) {
                    // Get old RGB values
                    byte oldRed = (byte)(sourcePtr[i] >> 16);
                    byte oldGreen = (byte)(sourcePtr[i] >> 8);
                    byte oldBlue = (byte)sourcePtr[i];

                    // Calculate & set new RGB values
                    destPtr[i] = (255 - oldRed) << 16 | (255 - oldGreen) << 8 | 255 - oldBlue;
                }
            }

            sourceImage.UnlockBits(source);
            image.UnlockBits(dest);            
            return image;
        }
    }
}
